package com.rename.wechat.weixin.checkurl;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

import com.rename.wechat.weixin.WeixinConfig;

public class Signature {
	
	private static final String token = WeixinConfig.TOKEN;
	
	public static boolean checkSignature(String signature, String timestamp, String nonce){
		
		String[] strArr = new String[]{token, timestamp, nonce};
		// 字典排序
		Arrays.sort(strArr);
		
		// 拼接成字符串
		StringBuilder content = new StringBuilder();
		for(int i = 0; i < strArr.length; i++){
			content.append(strArr[i]);
		}
		
		// sha1加密
		MessageDigest messageDigest = null;
		String tmpStr = null;

		try {

			messageDigest = MessageDigest.getInstance("SHA-1");
			byte[] digest = messageDigest.digest(content.toString().getBytes());
			tmpStr = byteToHexStr(digest);

		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}

		content = null;
		return tmpStr != null ? tmpStr.equalsIgnoreCase(signature) : false;
	}
	
	public static String byteToHexStr(byte[] b) {
		String des = "";
		String tmp = null;
		for (int i = 0; i < b.length; i++) {
			tmp = (Integer.toHexString(b[i] & 0xFF));
			if (tmp.length() == 1) {
				des += "0";
			}
			des += tmp;
		}
		return des;
	}

}
